import axios from 'axios';
import { Message } from 'element-ui';

// 创建axios实例
const event = axios.create({
  baseURL: '/materials',
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
});
// request拦截器
event.interceptors.request.use(
  (config) => {
    const tokenSign = sessionStorage.getItem('tokenSign');
    if (tokenSign) {
      config.headers['Authorization'] = tokenSign;
    }
    return config;
  },
  (error) => {
    console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
event.interceptors.response.use(
  (response) => {
    if (response.data.code && response.data.code !== 0) {
      if (response.data.message) {
        Message({
          message: response.data.message,
          type: 'error'
        })
      } else {
        Message({
          message: '请求网络错误',
          type: 'error'
        })
      }
      return Promise.reject(response.data)
    }
    if (response.data.code == 0) {
      return response.data
    }
    //用以返回blob数据
    return response
  },
  (error) => {
    console.log('err' + error);
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000,
    });
    return Promise.reject(error);
  }
);

export default event;
